package com.gitee.sdlszjb.page;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 庄壮壮
 * @since 2019-01-15 16:49
 */
@Component
public class AniviaPaginationFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        int offset = 0;
        int size = AniviaPaginationConstant.defaultPageSize;

        String offsetStr = "";
        String sizeStr = "";

        for (String s : AniviaPaginationConstant.pageKey) {
            String pageKey = request.getParameter(s);
            if (StringUtils.isNotBlank(pageKey)) {
                offsetStr = pageKey;
                break;
            }
        }

        for (String s : AniviaPaginationConstant.sizeKey) {
            String sizeKey = request.getParameter(s);
            if (StringUtils.isNotBlank(sizeKey)) {
                sizeStr = sizeKey;
                break;
            }
        }

        String orderStr = request.getParameter(AniviaPaginationConstant.orderKey);
        String sortStr = request.getParameter(AniviaPaginationConstant.sortKey);

        if (StringUtils.isNotBlank(offsetStr)) {
            offset = Integer.parseInt(offsetStr);
        }

        if (StringUtils.isNotBlank(sizeStr)) {
            size = Integer.parseInt(sizeStr);
        }

        try {
            AniviaPaginationRequest jpaAutoPaginationRequest = new AniviaPaginationRequest();
            jpaAutoPaginationRequest.setOrder(orderStr);
            jpaAutoPaginationRequest.setSort(sortStr);
            jpaAutoPaginationRequest.setPage(offset);
            jpaAutoPaginationRequest.setSize(size);
            jpaAutoPaginationRequest.setRequest(request);
            AniviaPaginationRequestHolder.initRequestHolder(jpaAutoPaginationRequest);
            filterChain.doFilter(request, response);
        } finally {
            AniviaPaginationRequestHolder.remove();
        }
    }

    @Override
    public void destroy() {
    }
}
